//
//  DetailViewController.m
//  UEHtml-iOS
//
//  Created by ShadowKnight on 13-10-5.
//  Copyright (c) 2013年 Qun He. All rights reserved.
//

#import "DetailViewController.h"
#import "UEServerInterface.h"
#import "UIConstanstDefine.h"
#import <QuartzCore/QuartzCore.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "Toast+UIView.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:UE_NORMAL_VIEW_FRAME];
    scroll.contentSize = CGSizeMake(CGRectGetWidth(UE_NORMAL_VIEW_FRAME), CGRectGetHeight(UE_NORMAL_VIEW_FRAME));
    scroll.alwaysBounceVertical = YES;
    scroll.delegate = self;
    self.view = scroll;
    [self.view setBackgroundColor:RGBCOLOR(224, 224, 224)];
    [self setTitle:self.caseTitle];
    
    [self initNaviBar];
    
    //--------initialized Data----//
    ueDetailSI = [[UEServerInterface alloc] initWithDelegate:self responseMethod:@selector(receivedDetailData:)];
    [self loadDetailDataFromServer];
}

-(void)initLoadingImage
{
    loadingGear = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(130, 200, 60, 60)];//指定进度轮的大小
    [loadingGear setCenter:CGPointMake(160, 140)];//指定进度轮中心点
    [loadingGear setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];//设置进度轮显示类型
    [self.view addSubview:loadingGear];
    [loadingGear startAnimating];
}

-(void)loadHeaderInfo
{
    UIImageView* headerBg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    [headerBg setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:headerBg];
    self.userPortrait = [[UIImageView alloc] initWithFrame:CGRectMake(10, 15, 50, 50)];
    self.userPortrait.layer.masksToBounds = YES;
    self.userPortrait.layer.cornerRadius = 25;
    [headerBg addSubview:self.userPortrait];
    
    //--------Header-Info icon layout-------------//
    float iconPosY = 47;
    float startPosX = CGRectGetMaxX(self.userPortrait.frame) + 20;
    float horizonDistance = 31 + CASECELL_WIDTH_OF_ICON;
    UIImageView *caseVisitIcon = [[UIImageView alloc] initWithFrame:CGRectMake(startPosX, iconPosY, CASECELL_WIDTH_OF_ICON, CASECELL_WIDTH_OF_ICON)];
    [caseVisitIcon setImage:IMAGE_BY_NAMED(@"case_accessed_normal.png")];
    [headerBg addSubview:caseVisitIcon];
    
    UIImageView *caseCommentIcon = [[UIImageView alloc] initWithFrame:CGRectMake(startPosX+horizonDistance, iconPosY, CASECELL_WIDTH_OF_ICON, CASECELL_WIDTH_OF_ICON)];
    [caseCommentIcon setImage:IMAGE_BY_NAMED(@"case_comment_normal.png")];
    [headerBg addSubview:caseCommentIcon];
    
    UIImageView *caseFavorateIcon = [[UIImageView alloc] initWithFrame:CGRectMake(startPosX+2*horizonDistance, iconPosY, CASECELL_WIDTH_OF_ICON, CASECELL_WIDTH_OF_ICON)];
    [caseFavorateIcon setImage:IMAGE_BY_NAMED(@"case_favorate_normal.png")];
    [headerBg addSubview:caseFavorateIcon];
    
    UIImageView *caseFromDateIcon = [[UIImageView alloc] initWithFrame:CGRectMake(275, 52, 9, 9)];
    [caseFromDateIcon setImage:IMAGE_BY_NAMED(@"case_date_icon.png")];
    [headerBg addSubview:caseFromDateIcon];
    
    nickName = [[UILabel alloc] initWithFrame:CGRectMake(80, 21, 220, 18)];
    [nickName setBackgroundColor:[UIColor clearColor]];
    [nickName setFont:[UIFont systemFontOfSize:18]];
    [headerBg addSubview:nickName];
    
    //--------Multi count lable initialized-----//
    caseVisitCount = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(caseVisitIcon.frame)+2, CGRectGetMidY(caseVisitIcon.frame)-4, CASECELL_WIDTH_OF_COUNT_LABEL, 8)];
    [caseVisitCount setFont:[UIFont systemFontOfSize:8.0f]];
    [caseVisitCount setText:@""];
    [caseVisitCount setTextColor:CASECELL_FONTCOLOR_COUNT_DESC];
    [caseVisitCount setBackgroundColor:[UIColor clearColor]];
    [headerBg addSubview:caseVisitCount];
    
    caseCommentCount = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(caseCommentIcon.frame)+2, CGRectGetMidY(caseCommentIcon.frame)-4, CASECELL_WIDTH_OF_COUNT_LABEL, 8)];
    [caseCommentCount setFont:[UIFont systemFontOfSize:8.0f]];
    [caseCommentCount setText:@""];
    [caseCommentCount setTextColor:CASECELL_FONTCOLOR_COUNT_DESC];
    [caseCommentCount setBackgroundColor:[UIColor clearColor]];
    [headerBg addSubview:caseCommentCount];
    
    caseFavorateCount = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(caseFavorateIcon.frame)+2, CGRectGetMidY(caseFavorateIcon.frame)-4, CASECELL_WIDTH_OF_COUNT_LABEL, 8)];
    [caseFavorateCount setFont:[UIFont systemFontOfSize:8.0f]];
    [caseFavorateCount setText:@""];
    [caseFavorateCount setTextColor:CASECELL_FONTCOLOR_COUNT_DESC];
    [caseFavorateCount setBackgroundColor:[UIColor clearColor]];
    [headerBg addSubview:caseFavorateCount];
    
    dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(caseFromDateIcon.frame)+2, CGRectGetMidY(caseFromDateIcon.frame)-4, 26, 6)];
    [dateLabel setFont:[UIFont systemFontOfSize:6.0f]];
    [dateLabel setText:@""];
    [dateLabel setTextColor:CASECELL_FONTCOLOR_COUNT_DESC];
    [dateLabel setBackgroundColor:[UIColor clearColor]];
    [headerBg addSubview:dateLabel];
    
    //--------Case content image-------//
    caseOrgImage = [[EGOImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(headerBg.frame), caseOrgImage.image.size.width, caseOrgImage.image.size.height)];
    [caseOrgImage setBackgroundColor:[UIColor clearColor]];
    caseOrgImage.delegate = self;
    [self.view addSubview:caseOrgImage];
}

-(void)initNaviBar
{
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 38, 32)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"Back_button_normal.png"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:IMAGE_BY_NAMED(@"Back_button_select.png") forState:UIControlStateHighlighted];
//    backBtn.showsTouchWhenHighlighted = YES;
    [backBtn addTarget:self action:@selector(backBarBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
}

-(void)backBarBtnTapped:(UIButton*)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadDetailDataFromServer
{
    [ueDetailSI ueHtml_getCaseByID:self.caseID];
}

-(void)receivedDetailData:(UEServerInterface*)sender
{
    NSLog(@"%@", sender.dict);
//    detailDatasource = [[NSMutableArray alloc] initWithArray:(NSArray*)sender.dict];
    [self loadHeaderInfo];
    [self.userPortrait setImageFromURL:[NSURL URLWithString:[sender.dict objectForKey:@"userimage"]]];
    [nickName setText:[sender.dict objectForKey:@"nickname"]];
    
    [caseVisitCount setText:[sender.dict objectForKey:@"views"]];
    [caseCommentCount setText:[sender.dict objectForKey:@"comments"]];
    [caseFavorateCount setText:[sender.dict objectForKey:@"likes"]];
    [dateLabel setText:[sender.dict objectForKey:@"postdate"]];
    
    [self initLoadingImage];
    [caseOrgImage setImageURL:[NSURL URLWithString:[[[sender.dict objectForKey:@"images"] objectAtIndex:0] objectForKey:@"url"]]];
//    [caseOrgImage setImageFromURL:[NSURL URLWithString:[[[sender.dict objectForKey:@"images"] objectAtIndex:0] objectForKey:@"url"]] placeHolderImage:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)imageViewHasLoadedImage:(UIImageView *)imageView
{
    CGRect realFrame = caseOrgImage.frame;
    
    if(imageView.image.size.width > 320)
    {
        realFrame.size.width = 320;
        realFrame.size.height = imageView.image.size.height*(320/imageView.image.size.width);
    }
    else
    {
        realFrame.size = imageView.image.size;
    }
    caseOrgImage.frame = realFrame;
    UIScrollView* detailView = (UIScrollView*)self.view;
    detailView.contentSize = CGSizeMake(320, realFrame.size.height+80);
}

#pragma mark -EGOImageViewDelegate
//#if 0
- (void)imageViewLoadedImage:(EGOImageView*)imageView
{
    [loadingGear stopAnimating];
    //    if(imageView.image == nil)
    //        [imageView setPlaceholderImage:IMAGENAEM(@"CPXQ_NoPic")];
    CGRect realFrame = caseOrgImage.frame;
    
    if(imageView.image.size.width > 320)
    {
        realFrame.size.width = 320;
        realFrame.size.height = imageView.image.size.height*(320/imageView.image.size.width);
    }
    else
    {
        realFrame.size = imageView.image.size;
    }
    caseOrgImage.frame = realFrame;
    UIScrollView* detailView = (UIScrollView*)self.view;
    detailView.contentSize = CGSizeMake(320, realFrame.size.height+80);
    [self addLongPressEvent4ImageView];
}
- (void)updateProgressImage:(EGOImageView*)imageView per:(NSNumber*)per
{
    
}

- (void)imageViewFailedToLoadImage:(EGOImageView*)imageView error:(NSError*)error
{
    
}

-(void)imageFinishedImage:(EGOImageView *)imageView
{
    [loadingGear stopAnimating];
//    [self stopLoadingAnimation];
    CGRect realFrame = caseOrgImage.frame;
    
    if(imageView.image.size.width > 320)
    {
        realFrame.size.width = 320;
        realFrame.size.height = imageView.image.size.height*(320/imageView.image.size.width);
    }
    else
    {
        realFrame.size = imageView.image.size;
    }
    caseOrgImage.frame = realFrame;
    UIScrollView* detailView = (UIScrollView*)self.view;
    detailView.contentSize = CGSizeMake(320, realFrame.size.height+80);
    [self addLongPressEvent4ImageView];
}

-(void)addLongPressEvent4ImageView
{
    //长按手势
    UILongPressGestureRecognizer *longGnizer=nil;
    longGnizer=[[UILongPressGestureRecognizer alloc]initWithTarget:self
                                                            action:@selector(longPressForShowSaveButton)];
    longGnizer.minimumPressDuration = 0.5;
    [caseOrgImage setUserInteractionEnabled:YES];
    [caseOrgImage addGestureRecognizer:longGnizer];
}

-(void)longPressForShowSaveButton
{
    UIControl* v = (UIControl*)[self.view viewWithTag:1000];
    if(v == nil)
    {
        UIControl* flowView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        flowView.tag = 1000;
        [self.view addSubview:flowView];
        
        saveButton = [[UIButton alloc] initWithFrame:CGRectMake(130, 200, 60, 45)];
        [saveButton setBackgroundColor:[UIColor blackColor]];
        [saveButton setTitle:@"保存" forState:UIControlStateNormal];
        [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        saveButton.layer.borderWidth = 2.0f;
        saveButton.layer.cornerRadius = 12.0f;
        saveButton.layer.borderColor = [UIColor whiteColor].CGColor;
        [saveButton addTarget:self action:@selector(saveImageToAlbum) forControlEvents:UIControlEventTouchUpInside];
        
        [flowView addSubview:saveButton];
        [flowView addTarget:self action:@selector(hideSaveButton) forControlEvents:UIControlEventTouchUpInside];
    }
}

-(void)hideSaveButton
{
    UIControl* v = (UIControl*)[self.view viewWithTag:1000];
    [saveButton removeFromSuperview];
    [v removeFromSuperview];
}

-(void)saveImageToAlbum
{
    [self hideSaveButton];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    
    [library writeImageDataToSavedPhotosAlbum:UIImageJPEGRepresentation(caseOrgImage.image, 1.0f)
                                     metadata:nil
                              completionBlock:^(NSURL *assetURL,NSError *error){
                                  
                                  [self.view makeToast:@"图片保存成功" duration:2.0 position:@"center"];
                                  
//                                  saveImage.hidden = YES;
                              }
     ];

}
//#endif//0

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self hideSaveButton];
}

@end
